<template>
  <view class="uni-wrap">
    <scroll-view class="pb-50">
      <view class="my-card-view">
        <uni-forms ref="form" :border="true" :model="formData" :rules="rules" err-show-type="toast">
          <template>
            <uni-card title="基本信息" :is-shadow="false" :border="false">
              <uni-forms-item label="单据日期" name="voucherDate" :label-width="labelWidth" required>
                <uni-datetime-picker type="date" v-model="formData.voucherDate" />
              </uni-forms-item>
              <uni-forms-item label="单据编码" name="code" :label-width="labelWidth" required>
                <uni-easyinput
                  v-model="formData.code"
                  placeholder="自动带入"
                  :disabled="true"
                  :inputBorder="false"
                />
              </uni-forms-item>
              <uni-forms-item label="客户" name="customerCode" :label-width="labelWidth" required>
                <text class="form-text" @click="goToChooseCustomer()">{{formData.customerName}}</text>
                <!-- <as-select
                  v-model="formData.customerCode"
                  title="选择客户"
                  placeholder="请选择"
                  :options="customerList"
                  labelKey="Name"
                  valueKey="Code"
                  @change="customerChange"
                />-->
              </uni-forms-item>
              <uni-forms-item
                label="结算客户"
                name="settleCustomerName"
                :label-width="labelWidth"
                required
              >
                <uni-easyinput
                  v-model="formData.settleCustomerName"
                  placeholder="自动带入"
                  :disabled="true"
                  :inputBorder="false"
                />
              </uni-forms-item>
              <uni-forms-item label="业务员" name="clerk" :label-width="labelWidth" required>
                <text class="form-text" @click="goToChoosePerson()">{{formData.clerkName}}</text>
                <!-- <as-select
                  v-model="formData.clerk"
                  title="选择业务员"
                  placeholder="请选择"
                  :options="clerkList"
                  labelKey="name"
                  valueKey="code"
                />-->
              </uni-forms-item>
              <uni-forms-item label="部门" name="deptName" :label-width="labelWidth" required>
                <uni-easyinput
                  v-model="formData.deptName"
                  placeholder="自动带入"
                  :disabled="true"
                  :inputBorder="false"
                />
              </uni-forms-item>
              <uni-forms-item label="币种" name="currencyLabel" :label-width="labelWidth" required>
                <uni-easyinput
                  v-model="formData.currencyLabel"
                  placeholder="币种"
                  :disabled="true"
                  :inputBorder="false"
                />
              </uni-forms-item>
              <uni-forms-item label="汇率" name="rate" :label-width="labelWidth" required>
                <uni-easyinput
                  v-model="formData.rate"
                  placeholder="汇率"
                  :disabled="true"
                  :inputBorder="false"
                />
              </uni-forms-item>
              <uni-forms-item label="预交货日期" name="deliveryDate" :label-width="labelWidth">
                <uni-datetime-picker type="date" v-model="formData.deliveryDate" />
              </uni-forms-item>
              <uni-forms-item label="合同号" name="contract" :label-width="labelWidth">
                <uni-easyinput
                  v-model="formData.contract"
                  placeholder="请输入合同号"
                  :inputBorder="false"
                />
              </uni-forms-item>
              <uni-forms-item
                label="业务类型"
                name="businessTypeLabel"
                :label-width="labelWidth"
                required
              >
                <uni-easyinput
                  v-model="formData.businessTypeLabel"
                  placeholder="普通销售"
                  :disabled="true"
                  :inputBorder="false"
                />
              </uni-forms-item>
            </uni-card>
            <uni-card title="订单明细" :is-shadow="false" :border="false">
              <view
                class="item"
                v-for="(item, index) in formData.saOrderDetailList"
                :key="index"
                style="border-bottom: 4px solid #eee;"
              >
                <uni-forms-item
                  :label="'存货' + (index+ 1)"
                  name="inventory"
                  :label-width="labelWidth"
                >
                  <view class="bao-view">
                    <button type="primary" size="mini" @click="goToChooseStock(index)">选择</button>

                    <view class="delete" @click="itemDelete(index)">
                      <text class="uni-card-error">删除</text>
                    </view>
                  </view>
                </uni-forms-item>
                <uni-forms-item
                  label="存货名称"
                  :name="['saOrderDetailList', index, 'inventoryName']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].inventoryName"
                    placeholder="自动带入"
                    :disabled="true"
                    :inputBorder="false"
                  />
                </uni-forms-item>
                <uni-forms-item
                  label="存货编码"
                  :name="['saOrderDetailList', index, 'inventoryCode']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].inventoryCode"
                    placeholder="自动带入"
                    :disabled="true"
                    :inputBorder="false"
                  />
                </uni-forms-item>

                <uni-forms-item
                  label="规格型号"
                  :name="['saOrderDetailList', index, 'specification']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].specification"
                    placeholder="自动带入"
                    :disabled="true"
                    :inputBorder="false"
                  />
                </uni-forms-item>
                <uni-forms-item
                  label="单位"
                  :name="['saOrderDetailList', index, 'unit']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].unit"
                    placeholder="自动带入"
                    :disabled="true"
                    :inputBorder="false"
                  />
                </uni-forms-item>
                <uni-forms-item
                  label="税率"
                  :name="['saOrderDetailList', index, 'taxRate']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].taxRate"
                    placeholder="自动带入"
                    :disabled="true"
                    :inputBorder="false"
                  />
                </uni-forms-item>

                <uni-forms-item
                  label="现存量"
                  :name="['saOrderDetailList', index, 'existingQuantity']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].existingQuantity"
                    placeholder="自动带入"
                    :disabled="true"
                    :inputBorder="false"
                  />
                </uni-forms-item>
                <uni-forms-item
                  label="可用量"
                  :name="['saOrderDetailList', index, 'availableQuantity']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].availableQuantity"
                    placeholder="自动带入"
                    :disabled="true"
                    :inputBorder="false"
                  />
                </uni-forms-item>
                <uni-forms-item
                  label="含税单价"
                  :name="['saOrderDetailList', index, 'origTaxPrice']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].origTaxPrice"
                    :placeholderStyle="placeholderStyle"
                    placeholder="含税单价"
                  />
                </uni-forms-item>

                <uni-forms-item
                  label="数量"
                  :name="['saOrderDetailList', index, 'quantity']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    v-model="formData.saOrderDetailList[index].quantity"
                    :placeholderStyle="placeholderStyle"
                    placeholder="数量"
                  />
                </uni-forms-item>

                <uni-forms-item
                  label="含税金额"
                  :name="['saOrderDetailList', index, 'origTaxAmount']"
                  :label-width="labelWidth"
                >
                  <uni-easyinput
                    :value="calculation(formData.saOrderDetailList[index].origTaxPrice, formData.saOrderDetailList[index].quantity, formData.saOrderDetailList[index])"
                    :placeholderStyle="placeholderStyle"
                    placeholder="自动计算"
                  />
                </uni-forms-item>
              </view>

              <view class="add-view">
                <button type="primary" size="mini" @click="itemAdd()" class="add-btn">+ 添加一行</button>
                <button
                  type="warn"
                  size="mini"
                  @click="getHistory()"
                  class="add-btn"
                  style="margin-left: 4px;"
                  v-if="formData.customerCode"
                >查询历史</button>
              </view>
            </uni-card>
          </template>
        </uni-forms>
      </view>
    </scroll-view>

    <view class="bottomFixed">
      <view class="btn-box">
        <button type="primary" class="btn-main" @click="submit('form')">确定</button>
      </view>
    </view>
  </view>
</template>

<script>
import moment from "moment";
import zqsSelect from "@/uni_modules/zqs-select/zqs-select.vue";
import { Decrypt } from "@/common/util";

export default {
  components: {
    zqsSelect
  },
  data() {
    return {
      placeholderStyle: "font-size: 14px",
      labelWidth: 100,
      formData: {
        voucherDate: moment().format("YYYY-MM-DD"),
        customerCode: null,
        customerName: "请选择客户",
        settleCustomerCode: null,
        settleCustomerName: "",
        clerkName: "请选择业务员",
        currency: "RMB",
        currencyLabel: "人民币(RMB)",
        rate: "1.000000",
        businessType: "15",
        businessTypeLabel: "普通销售",
        saOrderDetailList: []
      },
      rules: {
        customerCode: {
          rules: [
            {
              required: true,
              errorMessage: "请选择客户"
            }
          ]
        },
        clerk: {
          rules: [
            {
              required: true,
              errorMessage: "请选择业务员"
            }
          ]
        }
      },
      customerList: [], //客户列表
      clerkList: []
    };
  },
  onLoad() {
    // this.itemAdd();
  },
  methods: {
    calculation(origTaxPrice, quantity, row) {
      console.log("calc 单价 * 数量：", origTaxPrice, quantity);
      let value = origTaxPrice * quantity;
      row.origTaxAmount = value;
      if (!!value) {
        row.origTaxAmount = value;
        return value.toFixed(4);
      } else {
        row.origTaxAmount = 0;
        return 0;
      }
    },
    //添加行
    itemAdd() {
      let obj = {
        inventoryCode: null,
        inventoryName: "",
        specification: "",
        unit: "",
        taxRate: "",
        origTaxPrice: 0,
        quantity: 0,
        origTaxAmount: 0,
        existingQuantity: "",
        availableQuantity: ""
      };
      this.formData.saOrderDetailList.push(obj);
    },

    itemDelete(index) {
      this.formData.saOrderDetailList.splice(index, 1);
    },

    goToChooseCustomer() {
      let that = this;
      uni.navigateTo({
        url: "/pagesCommon/common/customerChoose",
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          acceptDataFromPage: function(res) {
            const data = res.data;
            if (data) {
              that.formData.customerCode = data.customerCode;
              that.formData.customerName = data.customerName;
              that.formData.settleCustomerCode = data.settleCode;
              that.formData.settleCustomerName = data.settleName;
            }
          }
        }
      });
    },
    goToChoosePerson() {
      let that = this;
      uni.navigateTo({
        url: "/pagesCommon/common/personChoose",
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          acceptDataFromPage: function(res) {
            const data = res.data;
            if (data) {
              that.formData.clerk = data.personCode;
              that.formData.clerkName = data.personName;
              that.formData.deptCode = data.deptCode;
              that.formData.deptName = data.deptName;
            }
          }
        }
      });
    },
    // getCustomerList() {
    //   this.$post("/tdata/customer/query", {}).then(res => {
    //     this.customerList = res.data;
    //   });
    // },

    goToChooseStock(index) {
      let that = this;
      uni.navigateTo({
        url: "/pagesCommon/common/stockChoose",
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          acceptDataFromPage: function(res) {
            const data = res.data;
            console.log("receive data", data);
            if (data) {
              that.formData.saOrderDetailList[index].inventoryCode = data.code;
              that.formData.saOrderDetailList[index].inventoryName = data.name;
              that.formData.saOrderDetailList[index].specification =
                data.specification;
              that.formData.saOrderDetailList[index].unit = data.unit;
              that.formData.saOrderDetailList[index].taxRate = data.taxRate;
              that.formData.saOrderDetailList[index].existingQuantity =
                data.existingQuantity;
              that.formData.saOrderDetailList[index].availableQuantity =
                data.availableQuantity;
            }
          }
        }
      });
    },

    getHistory() {
      let _self = this;
      uni.showModal({
        title: "提示",
        content: "是否查询该客户的历史订单数据？",
        success: function(res) {
          if (res.confirm) {
            console.log("用户点击确定");
            _self.$post("/sale/order/findByCustomer", {
              customerCode: _self.formData.customerCode
            }).then(res => {
              if (res.code == 200) {
                let detailList = res.data.saOrderDetailList;
                 detailList.map(item => {
                  item.id = null;
                 })
                 console.log("detailList", detailList)
                _self.formData.saOrderDetailList =
                 detailList || [];
              }
            });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        }
      });
    },
    submit(ref) {
      this.$refs[ref].validate().then(formDatas => {
        uni.showLoading({
          title: "提交中...",
          mask: true
        });
        let subParams = {
          // icFinprodinH: {
          //   cwarehouseid: this.formData.cwarehouseid,
          //   cdeptvid: this.formData.cdeptvid
          // },
          // saOrderDetailList: this.formData.saOrderDetailList
          ...this.formData
        }

        let url = "/sale/order";
        console.log(subParams);
        this.$post(url, subParams).then(res => {
          uni.hideLoading();
          if (res && res.code == 200) {
            uni.showModal({
              title: "提示",
              content: "添加销售订单成功",
              success: function() {
                uni.navigateTo({
                  url: "/pages/saleManage/saleOrder/list"
                });
                // uni.navigateBack({
                //   delta: 1
                // });
              }
            });
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none"
            });
          }
        });
      });
    }
  }
};
</script>

<style lang="scss">
.add-view {
  margin-bottom: 20rpx;
  .sub-list {
    .item {
      margin-bottom: 8px;
      .header-view {
        display: flex;
        background: #e9edfc;
        align-items: center;
        padding: 6rpx 18rpx;
        .header-title {
          border-radius: 10rpx 10rpx 0rpx 0rpx;
          font-size: 24rpx;
          color: #78797b;
          flex: 1;
        }
      }
    }
  }
}

.bao-view {
  display: flex;
  align-items: center;
  justify-content: space-between;

  uni-button {
    margin: 0;
  }
}
// .add-view {
//   display: flex;
//   align-items: center;
//   justify-content: space-between;
// }
.add-btn {
  margin: 10px 0;
}

.flex-row {
  display: flex;
  align-items: center;
}
</style>
